package net.caixiaomi.info.ui.mine;

import android.Manifest;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;

import net.caixiaomi.info.R;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseActivity;
import net.caixiaomi.info.base.permissions.Permission;
import net.caixiaomi.info.base.permissions.RxPermissions;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.UserInfoModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.ui.dialog.NickNameDialogFragment;
import net.caixiaomi.info.util.Constants;
import net.caixiaomi.info.util.FileHelper;
import net.caixiaomi.info.widgets.BottomHandleDialogFragment;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import retrofit2.Call;

public class PersonalInfoActivity extends BaseActivity implements BottomHandleDialogFragment.OnItemClickListener {
    private static final int CODE_CAMERA_REQUEST = 1000;
    private static final int CODE_GALLERY_REQUEST = 1001;
    private static final int CODE_RESULT_REQUEST = 1002;
    @BindView(R.id.phone)
    TextView mPhone;
    @BindView(R.id.password)
    TextView mPass;
    @BindView(R.id.image)
    ImageView mIcon;
    @BindView(R.id.nick)
    TextView mNick;
    @BindView(R.id.btn_identify)
    View mBtnIdentify;
    @BindView(R.id.view1)
    View mIdentifyDivider;
    @BindView(R.id.identify)
    TextView mIdentify;


    private Uri mImageUri;
    private Uri mOutUri;

    @OnClick(R.id.btn_icon)
    void toChooseImage() {
        BottomHandleDialogFragment dialogFragment = new BottomHandleDialogFragment();
        dialogFragment.setLayoutType(BottomHandleDialogFragment.LIST);
        dialogFragment.setMenu(R.menu.choose_image);
        dialogFragment.setItemClickListener(this);
        dialogFragment.show(getSupportFragmentManager(), dialogFragment.getClass().getName());
    }

    @OnClick(R.id.btn_nick)
    void toChangeNickName() {
        UserInfoModel userInfo = CommonApp.getUserInfo();
        if (!TextUtils.isEmpty(userInfo.getNickName()))
            return;
        NickNameDialogFragment dialogFragment = new NickNameDialogFragment();
        dialogFragment.show(getSupportFragmentManager(), dialogFragment.getClass().getName());
    }

    /**
     * 实名认证
     */
    @OnClick(R.id.btn_identify)
    void toIdentify() {
        UserInfoModel userInfo = CommonApp.getUserInfo();
        if (TextUtils.equals(userInfo.getIsReal(), "1"))
            return;
        Intent intent = new Intent(this, IdentifyActivity.class);
        startActivity(intent);
    }

    @Override
    protected int layout() {
        return R.layout.act_personal_info;
    }

    @OnClick(R.id.password)
    void toSetPassword() {
        Intent intent = new Intent(this, FixPasswordActivity.class);
        startActivity(intent);
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


    }

    @Override
    protected void onResume() {
        super.onResume();
        UserInfoModel userInfo = CommonApp.getUserInfo();
        if (userInfo != null) {
            updateUserState(userInfo);
        }
        refreshData();
    }

    private void refreshData() {
        JSONObject params = new JSONObject();
        params.put("time", String.valueOf(System.currentTimeMillis()));
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<UserInfoModel>> userInfoExceptPass = requestService.userInfoExceptPass(params);
        userInfoExceptPass.enqueue(new ResponseCallback<BaseCallModel<UserInfoModel>>(this) {
            @Override
            public void onSuccess(BaseCallModel<UserInfoModel> data) {
                //更新userInfo数据
                UserInfoModel userInfo = data.data;
                updateUserState(userInfo);
            }

            @Override
            public void onFail(ResponseError error) {

            }

            @Override
            public void onError() {
            }
        });
    }

    private void updateUserState(UserInfoModel userInfo) {
        try {
//        RequestOptions placeholder = RequestOptions.placeholderOf(R.mipmap.ic_default_head).circleCrop();
//        Glide.with(this).load().apply(placeholder).crossFade(1000).into(mIcon);
            mPhone.setText(userInfo.getMobile());
            mPass.setText(TextUtils.equals(userInfo.getHasPass(), "1") ? R.string.C_CHANGE_PW : R.string.C_SETTING_PW);
//        mNick.setText(TextUtils.isEmpty(userInfo.getNickName()) ? getString(R.string.C_NICK_PRE_FIX) : userInfo.getNickName());
//        mNick.setTextColor(ContextCompat.getColor(CommonApp.getInstance(), !TextUtils.isEmpty(userInfo.getNickName()) ? R.color.third_text : R.color.blue));
            boolean dealVersion = CommonApp.STORE.getBoolean(Constants.KEY_DEAL_VERSION, false);
            mBtnIdentify.setVisibility(dealVersion ? View.VISIBLE : View.GONE);
            mIdentifyDivider.setVisibility(dealVersion ? View.VISIBLE : View.GONE);
            mIdentify.setText(!TextUtils.equals(userInfo.getIsReal(), "1") ? getString(R.string.C_PRE_IDENTIFY) : userInfo.getRealInfo());
            mIdentify.setTextColor(ContextCompat.getColor(CommonApp.getInstance(), TextUtils.equals(userInfo.getIsReal(), "1") ? R.color.primary_text : R.color.orange_primary));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onItemClick(View view) {
        switch (view.getId()) {
            case R.id.btn_camera:
                checkPermissionAndTakePicture();
                break;
            case R.id.btn_gallery:
                choosePicture();
                break;

        }
    }

    private void takePicture() {
        try {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (intent.resolveActivity(getPackageManager()) != null) {
                File outputMediaFile = FileHelper.getOutputMediaFile();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    mImageUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", outputMediaFile);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } else {
                    mImageUri = Uri.fromFile(outputMediaFile);
                }
                intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);

                List<ResolveInfo> resInfoList = getPackageManager()
                        .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
                for (ResolveInfo resolveInfo : resInfoList) {
                    String packageName = resolveInfo.activityInfo.packageName;
                    grantUriPermission(packageName, mImageUri, Intent.FLAG_GRANT_READ_URI_PERMISSION
                            | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                }

                startActivityForResult(intent, CODE_CAMERA_REQUEST);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void choosePicture() {
        Intent pickIntent = new Intent(Intent.ACTION_PICK, null);
        pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(pickIntent, CODE_GALLERY_REQUEST);
    }

    private void cropImage() {
        try {
            File outputMediaFile = FileHelper.getOutputMediaFile();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                mOutUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", outputMediaFile);
            } else {
                mOutUri = Uri.fromFile(outputMediaFile);
            }

            Intent intent = new Intent("com.android.camera.action.CROP");

            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }
            intent.setDataAndType(mImageUri, "image/*");
            intent.putExtra("crop", "true");
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("scale", true);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mOutUri);
            intent.putExtra("outputX", 300);
            intent.putExtra("outputY", 300);
            intent.putExtra("return-data", false);

            List<ResolveInfo> resInfoList = getPackageManager()
                    .queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
            for (ResolveInfo resolveInfo : resInfoList) {
                String packageName = resolveInfo.activityInfo.packageName;
                grantUriPermission(packageName, mOutUri, Intent.FLAG_GRANT_READ_URI_PERMISSION
                        | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }

            for (ResolveInfo resolveInfo : resInfoList) {
                String packageName = resolveInfo.activityInfo.packageName;
                grantUriPermission(packageName, mImageUri, Intent.FLAG_GRANT_READ_URI_PERMISSION
                        | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            }

            startActivityForResult(intent, CODE_RESULT_REQUEST);


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void checkPermissionAndTakePicture() {
        RxPermissions mRxPermissions = new RxPermissions(this);
        mRxPermissions
                .requestEach(
                        Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            if (TextUtils.equals(permission.name, Manifest.permission.CAMERA)) {
                                takePicture();
                            }
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                        } else {
                            // 用户拒绝了该权限，并且选中『不再询问』
                        }
                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            if (resultCode == Activity.RESULT_OK) {
                if (requestCode == CODE_CAMERA_REQUEST) {
                    cropImage();
                } else if (requestCode == CODE_GALLERY_REQUEST) {
                    handleImage(data);
                } else if (requestCode == CODE_RESULT_REQUEST) {
                    if (Build.VERSION.SDK_INT >= 24) {
                        Bitmap bitmap = null;
                        try {
                            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(mOutUri));
                            mIcon.setImageBitmap(bitmap);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Bitmap bitmap = BitmapFactory.decodeFile(mOutUri.getPath());
                        mIcon.setImageBitmap(bitmap);
                    }
                }
            } else {
                super.onActivityResult(requestCode, resultCode, data);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handleImage(Intent data) {
        try {
            String imagePath = null;
            mImageUri = data.getData();
            if (DocumentsContract.isDocumentUri(this, mImageUri)) {
                String docId = DocumentsContract.getDocumentId(mImageUri);        //数据表里指定的行
                if ("com.android.providers.media.documents".equals(mImageUri.getAuthority())) {
                    String id = docId.split(":")[1];
                    String selection = MediaStore.Images.Media._ID + "=" + id;
                    imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
                } else if ("com.android.providers.downloads.documents".equals(mImageUri.getAuthority())) {
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
                    imagePath = getImagePath(contentUri, null);
                }
            } else if ("content".equalsIgnoreCase(mImageUri.getScheme())) {
                imagePath = getImagePath(mImageUri, null);
            } else if ("file".equalsIgnoreCase(mImageUri.getScheme())) {
                imagePath = mImageUri.getPath();
            }
            cropImage();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过uri和selection来获取真实的图片路径,从相册获取图片时要用
     */
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

}
